package com.kanshu.ksgb.fastread.doudou.module.message.manager;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v4.app.NotificationCompat;
import android.text.TextUtils;

import com.kanshu.ksgb.fastread.doudou.R;
import com.kanshu.ksgb.fastread.doudou.app.Xutils;
import com.kanshu.ksgb.fastread.doudou.app.constants.Constants;
import com.kanshu.ksgb.fastread.doudou.module.message.receiver.JPushReceiver;
import com.kanshu.ksgb.fastread.doudou.common.business.interfaces.IDisposeMessage;
import com.kanshu.ksgb.fastread.doudou.common.util.JsonUtils;
import com.kanshu.ksgb.fastread.doudou.common.util.Utils;
import com.kanshu.ksgb.fastread.doudou.common.business.commonbean.ReaderInputParams;
import com.kanshu.ksgb.fastread.doudou.common.business.commonbean.MessageBean;
import com.kanshu.ksgb.fastread.doudou.common.business.commonbean.NotifyBean;
import com.kanshu.ksgb.fastread.doudou.common.business.utils.UserUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import static android.content.Context.NOTIFICATION_SERVICE;

/**
 * Created by wcy on 2017\6\27 0027.
 */
public class MessageCenter {
    private List<IDisposeMessage> mIDisposeMessages;
    private volatile static MessageCenter sMessageCenter;
    public static String CHANNEL_NAME = "message";

    private MessageCenter() {
        mIDisposeMessages = new ArrayList<>();
    }
    public static MessageCenter getInstance() {
        if (sMessageCenter == null) {
            synchronized (MessageCenter.class) {
                if (sMessageCenter == null) {
                    sMessageCenter = new MessageCenter();
                }
            }
        }
        return sMessageCenter;
    }

    public void register(IDisposeMessage message) {
        if (message == null) {
            return;
        }
        if (mIDisposeMessages.contains(message)) {
            return;
        } else {
            mIDisposeMessages.add(message);
        }
    }

    public void unregister(IDisposeMessage message) {
        if (message == null) {
            return;
        }
        if (mIDisposeMessages.contains(message)) {
            mIDisposeMessages.remove(message);
        }
    }

    public void handleMessage(MessageBean bean) {
        // 通知栏消息不存数据库
        if (!TextUtils.isEmpty(bean.style_type)
                && Integer.parseInt(bean.style_type) == MessageBean.TYPE_MESSAGE_NOTIFY) {
            sendNotification(Xutils.getContext(), bean.notify);
            return;
        }
        for (int i = 0; i < mIDisposeMessages.size(); i++) {
            mIDisposeMessages.get(i).diposeMessage(bean);
        }
        MessageDao messageDao = new MessageDao(UserUtils.getUserId());
        // 插入或者更新数据
        messageDao.insertOrUpdate(bean);
    }

    /**
     * 发送通知消息
     * @param context
     */
    public void sendNotification(Context context, NotifyBean bean) {
        if (bean == null || TextUtils.isEmpty(bean.notify_link_type)) {
            return;
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            createNotificationChannel(CHANNEL_NAME, CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);
        }
        Notification notification;
        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        boolean flg = false;
        Intent resultIntent = new Intent();
        int notifyId = 1;
        if (!TextUtils.isEmpty(bean.notify_id) && Utils.isNumeric(bean.notify_id)) {
            notifyId = Integer.parseInt(bean.notify_id);
        }
        final int NOTIFICATION_ID = notifyId;
        flg = createIntent(context, resultIntent, bean);
        if (flg) {
            Intent clickIntent = new Intent(context, JPushReceiver.class);
            clickIntent.putExtra("realIntent", resultIntent);
            clickIntent.setAction(Constants.PUSH_RECEIVER_ACTION);
            PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, clickIntent, PendingIntent.FLAG_UPDATE_CURRENT);
            notification = new NotificationCompat.Builder(Xutils.getContext(), CHANNEL_NAME)
                    .setContentTitle(bean.notify_theme)
                    .setContentText(bean.notify_content)
                    .setWhen(System.currentTimeMillis())
                    .setSmallIcon(R.mipmap.logo)
                    .setLargeIcon(BitmapFactory.decodeResource(Xutils.getContext().getResources(), R.mipmap.logo))
                    .setAutoCancel(true)
                    .setOngoing(false)
                    .setContentIntent(pendingIntent)
                    .build();
            assert notificationManager != null;
            notificationManager.notify(NOTIFICATION_ID, notification);
        }
    }

    public static boolean createIntent(Context context, Intent resultIntent, NotifyBean bean) {
        int link_type = Integer.parseInt(bean.notify_link_type);
        int notifyId = 1;
        if (!TextUtils.isEmpty(bean.notify_id) && Utils.isNumeric(bean.notify_id)) {
            notifyId = Integer.parseInt(bean.notify_id);
        }
        boolean flg = false;
        resultIntent.putExtra("link_type", link_type);
        resultIntent.putExtra("notify_id", notifyId);
        resultIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        switch (link_type) {
            case Constants.JUMP_TYPE_READER:
                flg = true;
                processReaderJump(context, bean, resultIntent);
                break;
            case Constants.JUMP_TYPE_H5:
                flg = true;
                processH5Jump(context, bean, resultIntent);
                break;
            case Constants.JUMP_TYPE_NONE:
                // do nothing
                break;
            case Constants.JUMP_TYPE_BOOK_DETAIL:
                flg = true;
                // 跳转书详情
                processBookDetailsJump(context,bean, resultIntent);
                break;
            default:
                break;
        }
        return flg;
    }

    /**
     * 处理阅读器跳转
     * @param context
     * @param bean
     * @param resultIntent
     */
    private static void processReaderJump(Context context, NotifyBean bean, Intent resultIntent) {
        ReaderInputParams params = new ReaderInputParams();
        params.book_id = bean.notify_book_id;
        params.content_id = bean.notify_content_id;
        params.order = bean.notify_order_id;
        Uri uri = Uri.parse(getReaderUrl(context, params));
        resultIntent.setPackage(Xutils.getContext().getPackageName());
        resultIntent.setData(uri);
        // 解析参数
        Set<String> names = uri.getQueryParameterNames();
        if (names != null && names.size() > 0) {
            for (String name : names) {
                if (!TextUtils.isEmpty(name)) {
                    String val = uri.getQueryParameter(name);
                    resultIntent.putExtra(name, val);
                }
            }
        }
    }

    /**
     * 书籍详情跳转
     * @param context
     * @param bean
     * @param resultIntent
     */
    private static void processBookDetailsJump(Context context, NotifyBean bean, Intent resultIntent) {
        Uri uri = Uri.parse(getBookDetailsUrl(context, bean.notify_url));
        resultIntent.setPackage(Xutils.getContext().getPackageName());
        resultIntent.setData(uri);
        // 解析参数
        Set<String> names = uri.getQueryParameterNames();
        if (names != null && names.size() > 0) {
            for (String name : names) {
                if (!TextUtils.isEmpty(name)) {
                    String val = uri.getQueryParameter(name);
                    resultIntent.putExtra(name, val);
                }
            }
        }
    }

    /**
     * h5跳转
     * @param context
     * @param bean
     * @param resultIntent
     */
    private static void processH5Jump(Context context, NotifyBean bean, Intent resultIntent) {
        Uri uri = Uri.parse(getH5CommonH5Url(context, bean.notify_url, bean.notify_theme));
        resultIntent.setPackage(Xutils.getContext().getPackageName());
        resultIntent.setData(uri);
        // 解析参数
        Set<String> names = uri.getQueryParameterNames();
        if (names != null && names.size() > 0) {
            for (String name : names) {
                if (!TextUtils.isEmpty(name)) {
                    String val = uri.getQueryParameter(name);
                    resultIntent.putExtra(name, val);
                }
            }
        }
    }

    /**
     * @param context
     * @param bookId
     * @return
     */
    public static String getBookDetailsUrl(Context context, String bookId) {
        Map<String, String> map = new HashMap<>();
        map.put("book_id", bookId);
        StringBuilder sb = new StringBuilder();
        sb.append(context.getString(R.string.base_jump_url))
                .append(context.getString(R.string.book_detail));
        return Utils.linkUrl(sb.toString(), map);
    }

    /**
     * 获取通用的h5链接
     * @param context
     * @param url
     * @param title
     * @return
     */
    public static String getH5CommonH5Url(Context context, String url, String title) {
        Map<String, String> map = new HashMap<>();
        map.put("url", url);
        map.put("title", title);
        StringBuilder sb = new StringBuilder();
        sb.append(context.getString(R.string.base_jump_url))
                .append(context.getString(R.string.comm_url));
        return Utils.linkUrl(sb.toString(), map);
    }

    /**
     * 获取阅读器的跳转链接
     *
     * @param context
     * @param params
     * @return
     */
    public static String getReaderUrl(Context context, ReaderInputParams params) {
        Map<String, String> map = JsonUtils.jsonStrToMap(JsonUtils.bean2Json(params));
        StringBuilder sb = new StringBuilder();
        sb.append(context.getString(R.string.base_jump_url))
                .append(context.getString(R.string.reader));
        return Utils.linkUrl(sb.toString(), map);
    }
    @RequiresApi(api = Build.VERSION_CODES.O)
    private void createNotificationChannel(String channelId, String channelName, int importance) {
        NotificationChannel channel = new NotificationChannel(channelId, channelName, importance);
        NotificationManager notificationManager = (NotificationManager) Xutils.getContext().getSystemService(
                NOTIFICATION_SERVICE);
        notificationManager.createNotificationChannel(channel);
    }
}
